<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">









  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



















  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.jpg?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  




  <meta name="description" content="swagger什么 swagger自称为世界上最好用的接口文档框架。与这个这个世界之最的称号相比我们更关心它是否能帮助我们解决问题。 记得若干年前使用javadoc生成文档的时候经历了痛苦的配置。 本文将介绍如何将swagger整合到我们自己的接口服务项目里面去。不管你的项目是已经完成上线就等文档了还是开发刚刚开始，swagger的整合的过程都轻松无痛。 墙裂建议先把接口服务跑通保证正常运行，之后">
<meta property="og:type" content="article">
<meta property="og:title" content="spring下使用swagger接口服务">
<meta property="og:url" content="https://devzhao.com/post/ce66c137.html">
<meta property="og:site_name" content="学而时习之">
<meta property="og:description" content="swagger什么 swagger自称为世界上最好用的接口文档框架。与这个这个世界之最的称号相比我们更关心它是否能帮助我们解决问题。 记得若干年前使用javadoc生成文档的时候经历了痛苦的配置。 本文将介绍如何将swagger整合到我们自己的接口服务项目里面去。不管你的项目是已经完成上线就等文档了还是开发刚刚开始，swagger的整合的过程都轻松无痛。 墙裂建议先把接口服务跑通保证正常运行，之后">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://qnfile.devzhao.com/blog/2018-10-12-095020.png">
<meta property="og:image" content="https://qnfile.devzhao.com/blog/2018-10-12-095021.png">
<meta property="og:image" content="https://qnfile.devzhao.com/blog/2018-10-12-95022.png">
<meta property="og:image" content="https://qnfile.devzhao.com/blog/2018-10-12-095023.png">
<meta property="og:updated_time" content="2018-10-13T13:33:09.942Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="spring下使用swagger接口服务">
<meta name="twitter:description" content="swagger什么 swagger自称为世界上最好用的接口文档框架。与这个这个世界之最的称号相比我们更关心它是否能帮助我们解决问题。 记得若干年前使用javadoc生成文档的时候经历了痛苦的配置。 本文将介绍如何将swagger整合到我们自己的接口服务项目里面去。不管你的项目是已经完成上线就等文档了还是开发刚刚开始，swagger的整合的过程都轻松无痛。 墙裂建议先把接口服务跑通保证正常运行，之后">
<meta name="twitter:image" content="https://qnfile.devzhao.com/blog/2018-10-12-095020.png">






  <link rel="canonical" href="https://devzhao.com/post/ce66c137.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>spring下使用swagger接口服务 | 学而时习之</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b8fcd96e6d9e134b3c9551097ed074a4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div id="showImgFullScrn" style="display: none;"><img id="showImgFullScrnImg" src="" style="max-height:100%"></div>

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">学而时习之</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">时间就是力量</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-shortcut">
    <a href="/shortcut/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-shirtsinbulk"></i> <br />快捷</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://devzhao.com/post/ce66c137.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaohan">
      <meta itemprop="description" content="教，是最好的学">
      <meta itemprop="image" content="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学而时习之">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">spring下使用swagger接口服务
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2017-02-22 16:15:12" itemprop="dateCreated datePublished" datetime="2017-02-22T16:15:12+08:00">2017-02-22</time>
            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/post/ce66c137.html#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/post/ce66c137.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/post/ce66c137.html" class="leancloud_visitors" data-flag-title="spring下使用swagger接口服务">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">7k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <h1 id="swagger什么"><a href="#swagger什么" class="headerlink" title="swagger什么"></a>swagger什么</h1><p><img src="https://qnfile.devzhao.com/blog/2018-10-12-095020.png" alt=""></p>
<p>swagger自称为世界上最好用的接口文档框架。与这个这个世界之最的称号相比我们更关心它是否能帮助我们解决问题。</p>
<p>记得若干年前使用javadoc生成文档的时候经历了痛苦的配置。</p>
<p>本文将介绍如何将swagger整合到我们自己的接口服务项目里面去。不管你的项目是已经完成上线就等文档了还是开发刚刚开始，swagger的整合的过程都轻松无痛。</p>
<p><strong>墙裂建议先把接口服务跑通保证正常运行，之后再整合swagger</strong>，不然出错了你可能搞不清楚是项目本身的异常还是整合swagger的错误。</p>
<p>在网上搜索接口文档生成工具的时候会发现springfox这个工具。去看官方文档会发现以下简单的描述,所以就没有必要在两者之间进行选择了。</p>
<p><img src="https://qnfile.devzhao.com/blog/2018-10-12-095021.png" alt=""></p>
<hr>
<blockquote>
<p>把大象装进冰箱需要三步</p>
</blockquote>
<h1 id="1-添加pom依赖包"><a href="#1-添加pom依赖包" class="headerlink" title="1.添加pom依赖包"></a>1.添加pom依赖包</h1><p>注意以下是比较完整的依赖包，而不是仅仅引入一个swagger-springmvc.jar</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- swagger-springmvc --&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;com.mangofactory&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;swagger-springmvc&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;1.0.2&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;com.mangofactory&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;swagger-models&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;1.0.2&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;com.wordnik&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;swagger-annotations&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;1.3.11&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br><span class="line">   &lt;!-- swagger-springmvc dependencies --&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;com.google.guava&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;guava&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;15.0&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;jackson-annotations&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;2.4.4&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;2.4.4&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;jackson-core&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;2.4.4&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br><span class="line">   &lt;dependency&gt;</span><br><span class="line">       &lt;groupId&gt;com.fasterxml&lt;/groupId&gt;</span><br><span class="line">       &lt;artifactId&gt;classmate&lt;/artifactId&gt;</span><br><span class="line">       &lt;version&gt;1.1.0&lt;/version&gt;</span><br><span class="line">   &lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>读者可能会有疑问，maven管理的依赖包不是具有传递性吗？是的，是有传递性，但是传递性是根据<scope>来界定的。打开swagger-springmvc依赖包的pom文件可以发现，其很多依赖包的scope值为compile或者provider，不会根据传递性自动引入。</scope></p>
</blockquote>
<h1 id="2-建立swagger配置类"><a href="#2-建立swagger配置类" class="headerlink" title="2.建立swagger配置类"></a>2.建立swagger配置类</h1><p>下面的代码网上可以轻易找到。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line">* &lt;p&gt;Title: SwaggerConfig.java&lt;/p&gt;</span><br><span class="line">* &lt;p&gt;Description: &lt;/p&gt;</span><br><span class="line">* &lt;p&gt;Copyright: Copyright (c) 2017&lt;/p&gt;</span><br><span class="line">* @author zhaohan</span><br><span class="line">* @date Feb 22, 2017</span><br><span class="line">* @version 1.0</span><br><span class="line">*/</span><br><span class="line">package net.simplty.write.api.controller;</span><br><span class="line"></span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line">import org.springframework.context.annotation.Bean;</span><br><span class="line">import org.springframework.context.annotation.Configuration;</span><br><span class="line"></span><br><span class="line">import com.mangofactory.swagger.configuration.SpringSwaggerConfig;</span><br><span class="line">import com.mangofactory.swagger.models.dto.ApiInfo;</span><br><span class="line">import com.mangofactory.swagger.plugin.EnableSwagger;</span><br><span class="line">import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line">* &lt;p&gt;Title: SwaggerConfig&lt;/p&gt;</span><br><span class="line">* &lt;p&gt;Description: &lt;/p&gt;</span><br><span class="line">* @author    zhaohan</span><br><span class="line">* @date Feb 22, 2017</span><br><span class="line">*/</span><br><span class="line">@Configuration</span><br><span class="line">@EnableSwagger</span><br><span class="line">public class SwaggerConfig &#123;</span><br><span class="line">	private SpringSwaggerConfig springSwaggerConfig;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Required to autowire SpringSwaggerConfig</span><br><span class="line">     */</span><br><span class="line">    @Autowired</span><br><span class="line">    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig)</span><br><span class="line">    &#123;</span><br><span class="line">        this.springSwaggerConfig = springSwaggerConfig;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc</span><br><span class="line">     * framework - allowing for multiple swagger groups i.e. same code base</span><br><span class="line">     * multiple swagger resource listings.</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public SwaggerSpringMvcPlugin customImplementation()</span><br><span class="line">    &#123;</span><br><span class="line">        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)</span><br><span class="line">                .apiInfo(apiInfo())</span><br><span class="line">                .includePatterns(&quot;.*?&quot;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    private ApiInfo apiInfo()</span><br><span class="line">    &#123;</span><br><span class="line">        ApiInfo apiInfo = new ApiInfo(</span><br><span class="line">                &quot;My Apps API Title&quot;,</span><br><span class="line">                &quot;My Apps API Description&quot;,</span><br><span class="line">                &quot;My Apps API terms of service&quot;,</span><br><span class="line">                &quot;My Apps API Contact Email&quot;,</span><br><span class="line">                &quot;My Apps API Licence Type&quot;,</span><br><span class="line">                &quot;My Apps API License URL&quot;);</span><br><span class="line">        return apiInfo;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>需要注意的是别忘了加上以下的两个注解</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">@Configuration</span><br><span class="line">@EnableSwagger</span><br></pre></td></tr></table></figure>
<p>swagger配置类建立好了之后别忘了在spring的启动文件里面加上以下的bean，否则你会看到一个“注解异常的错误”</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean id=&quot;SpringSwaggerConfig&quot; class=&quot;com.mangofactory.swagger.configuration.SpringSwaggerConfig&quot; /&gt;</span><br></pre></td></tr></table></figure>
<hr>
<p>到目前为止，我们已经完成了对所有接口方法的扫描解析功能，那解析得到什么内容呢？这需要我们自定义，自定义操作的对象就是接口方法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">@Controller</span><br><span class="line">@Scope(&quot;prototype&quot;)</span><br><span class="line">@RequestMapping(&quot;/user&quot;)</span><br><span class="line">public class UserController&#123;</span><br><span class="line"></span><br><span class="line">   protected HttpServletRequest request;</span><br><span class="line">   protected HttpServletResponse response;</span><br><span class="line">   protected HttpSession session;</span><br><span class="line"></span><br><span class="line">   @ModelAttribute</span><br><span class="line">   public void setReqAndRes(HttpServletRequest request, HttpServletResponse response)&#123;</span><br><span class="line">       this.request = request;</span><br><span class="line">       this.response = response;</span><br><span class="line">       this.session = request.getSession();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">	@RequestMapping(&quot;/validateSessionKey&quot;)</span><br><span class="line">	@ResponseBody</span><br><span class="line">	@ApiOperation(value = &quot;验证客户端的session&quot;, httpMethod = &quot;GET&quot;, response = ApiResult.class, notes = &quot;验证客户端的session&quot;)</span><br><span class="line">	public JSONObject validateSessionKey(@ApiParam(required = true, name = &quot;sessionKey&quot;, value = &quot;sessionKey&quot;) </span><br><span class="line">				@RequestParam(value=&quot;sessionKey&quot;, required=true) String sessionKey) throws Exception&#123;</span><br><span class="line">	</span><br><span class="line">	   .....</span><br><span class="line">	   </span><br><span class="line">	   return json;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>@ApiOperation注解对这个方法进行了说明，@ApiParam注解对方法参数进行了说明。关于这两个注解的使用，可以参看源码。这样子，Swagger就可以扫描接口方法，得到我们自定义的接口说明内容。</p>
<p>Swagger扫描解析得到的是一个json文档，对于用户不太友好。<br><img src="https://qnfile.devzhao.com/blog/2018-10-12-95022.png" alt=""></p>
<h1 id="3-Swagger-UI配置"><a href="#3-Swagger-UI配置" class="headerlink" title="3.Swagger-UI配置"></a>3.Swagger-UI配置</h1><p>Swagger-UI是一种比较友好的展示方式，它能够友好的展示解析得到的接口说明内容。</p>
<p>本文项目的视图配置如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 视图解析器 --&gt;</span><br><span class="line">&lt;bean id=&quot;viewResolver&quot; class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;&gt;</span><br><span class="line">	&lt;property name=&quot;viewClass&quot;</span><br><span class="line">			value=&quot;org.springframework.web.servlet.view.JstlView&quot; /&gt;</span><br><span class="line">		&lt;property name=&quot;prefix&quot; value=&quot;/pages/&quot; /&gt;</span><br><span class="line">		&lt;property name=&quot;suffix&quot; value=&quot;.jsp&quot; /&gt;</span><br><span class="line">		&lt;property name=&quot;order&quot; value=&quot;0&quot;/&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<p>所有的视图放在/pages/下</p>
<ul>
<li>从<a href="https://github.com/swagger-api/swagger-ui" target="_blank" rel="noopener">https://github.com/swagger-api/swagger-ui</a> 获取其所有的 dist 目录下东西放到需要集成的项目里，<br>放入 src/main/webapp/pages/swagger/ 目录下。</li>
<li>修改swagger/index.html文件，默认是从连接<a href="http://petstore.swagger.io/v2/swagger.json获取" target="_blank" rel="noopener">http://petstore.swagger.io/v2/swagger.json获取</a> API 的 JSON，这里需要将url值修改为http://{ip}:{port}/{projectName}/api-docs的形式，{}中的值根据自身情况填写。比如我的url值为：<a href="http://localhost:8280/myapp/api-docs" target="_blank" rel="noopener">http://localhost:8280/myapp/api-docs</a><br>  因为swagger-ui项目都是静态资源，restful形式的拦截方法会将静态资源进行拦截处理，所以在springmvc配置文件中需要配置对静态文件的处理方式。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//所有swagger目录的访问，直接访问location指定的目录</span><br><span class="line">&lt;mvc:resources mapping=&quot;/swagger/**&quot; location=&quot;/pages/swagger/&quot;/&gt;</span><br></pre></td></tr></table></figure>
<ul>
<li>打开浏览器直接访问swagger目录下的index.html文件，即可看到接口文档说明了。</li>
</ul>
<p><strong>注意访问地址，不是index.html里面配置的</strong>   比如我的是：<a href="http://localhost:8280/myapp/swagger/index.html" target="_blank" rel="noopener">http://localhost:8280/myapp/swagger/index.html</a> </p>
<p><img src="https://qnfile.devzhao.com/blog/2018-10-12-095023.png" alt=""></p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持分享输出，感谢你的支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="zhaohan 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="zhaohan 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>zhaohan</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://devzhao.com/post/ce66c137.html" title="spring下使用swagger接口服务">https://devzhao.com/post/ce66c137.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/post/undefined.html" rel="next" title="从员工到经理的第一堂课：把任务分解为目标">
                <i class="fa fa-chevron-left"></i> 从员工到经理的第一堂课：把任务分解为目标
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/post/585c5232.html" rel="prev" title="springMvc之注解参数">
                springMvc之注解参数 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif"
                alt="zhaohan" />
            
              <p class="site-author-name" itemprop="name">zhaohan</p>
              <p class="site-description motion-element" itemprop="description">教，是最好的学</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">148</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">33</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">29</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#swagger什么"><span class="nav-number">1.</span> <span class="nav-text">swagger什么</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#1-添加pom依赖包"><span class="nav-number">2.</span> <span class="nav-text">1.添加pom依赖包</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-建立swagger配置类"><span class="nav-number">3.</span> <span class="nav-text">2.建立swagger配置类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-Swagger-UI配置"><span class="nav-number">4.</span> <span class="nav-text">3.Swagger-UI配置</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaohan</span>

  

  
</div>


  










        
<div class="busuanzi-count">
  <!--<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->

  <script async src="//cdn.busuanzi.ibruce.info/cdn/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <!-- <i class="fa fa-user-circle"></i> -->
      <i>已有</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      <i>位访客浏览过此网站</i>
    </span>
  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz',
        appKey: 'N7MTJbRdufk8MAg3yeK6Gs9U',
        placeholder: '说点什么吧...',
        avatar:'mm',
        meta:guest,
        pageSize:'10' || 10,
        visitor: false
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.time + 1);
            })
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1}))
                .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function () {
                  console.log('Failed to create');
                });
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz",
                'X-LC-Key': "N7MTJbRdufk8MAg3yeK6Gs9U",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  
  

  

  

  

  

  

</body>
</html>
